package web.stu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import web.stu.common.ErrorCode;
import web.stu.exception.BusinessException;
import web.stu.mapper.TeacherCourseMapper;
import web.stu.model.dto.teacherCourse.AddTeacherCourseDTO;
import web.stu.model.dto.teacherCourse.QueryTeacherCourseDTO;
import web.stu.model.entity.Class;
import web.stu.model.entity.Course;
import web.stu.model.entity.User;
import web.stu.model.enums.UserRoleEnum;
import web.stu.model.vo.TeacherCourseVO;
import web.stu.service.ClassService;
import web.stu.service.CourseService;
import web.stu.service.TeacherCourseService;
import web.stu.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeacherCourseServiceImpl implements TeacherCourseService {

    @Resource
    private UserService userService;

    @Resource
    private CourseService courseService;

    @Resource
    private ClassService classService;

    @Resource
    private TeacherCourseMapper teacherCourseMapper;

    @Override
    public Page<TeacherCourseVO> pageTeacherCourses(QueryTeacherCourseDTO queryTeacherCourseDTO, HttpServletRequest request) {
        // 非空判断
        if (queryTeacherCourseDTO == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR);
        }
        // 提取变量
        String teacherName = queryTeacherCourseDTO.getTeacherName();
        String className = queryTeacherCourseDTO.getClassName();
        String courseName = queryTeacherCourseDTO.getCourseName();
        long current = queryTeacherCourseDTO.getCurrent();
        long pageSize = queryTeacherCourseDTO.getPageSize();

        List<User> teacherList = userService.list(new QueryWrapper<User>()
                .select("id")
                .like(StrUtil.isNotBlank(teacherName), "real_name", teacherName)
                .eq("role", UserRoleEnum.TEACHER.getValue())
                .eq("status", 1));

        List<web.stu.model.entity.Class> classList = classService.list(new QueryWrapper<web.stu.model.entity.Class>()
                .select("id")
                .like(StrUtil.isNotBlank(className), "class_name", className));

        List<Course> courseList = courseService.list(new QueryWrapper<Course>()
                .select("id")
                .like(StrUtil.isNotBlank(courseName), "course_name", courseName));

        List<Integer> teacherIds = teacherList.stream().map(User::getId).collect(Collectors.toList());
        List<Integer> classIds = classList.stream().map(web.stu.model.entity.Class::getId).collect(Collectors.toList());
        List<Integer> courseIds = courseList.stream().map(Course::getId).collect(Collectors.toList());

        // 对于空列表，添加一个永远不会匹配的条件
        if (teacherIds.isEmpty()) {
            teacherIds.add(Integer.MIN_VALUE); // 或者其他不可能存在的值
        }
        if (classIds.isEmpty()) {
            classIds.add(Integer.MIN_VALUE);
        }
        if (courseIds.isEmpty()) {
            courseIds.add(Integer.MIN_VALUE);
        }

        // 查询
        Page<TeacherCourseVO> page = new Page<>(current, pageSize);
        IPage<TeacherCourseVO> teacherCourseVOIPage = teacherCourseMapper.pageTeacherCourse(classIds, courseIds, teacherIds, page);

        // 处理返回值  补充VO中的其他字段
        List<TeacherCourseVO> result = teacherCourseVOIPage.getRecords().stream().map(teacherCourseVO -> {
            User teacherTemp = userService.getById(teacherCourseVO.getTeacherId());
            web.stu.model.entity.Class classTemp = classService.getById(teacherCourseVO.getClassId());
            Course courseTemp = courseService.getById(teacherCourseVO.getCourseId());
            if (teacherTemp != null) {
                teacherCourseVO.setTeacherName(teacherTemp.getRealName());
            }
            if (classTemp != null) {
                teacherCourseVO.setClassName(classTemp.getClassName());
            }
            if (courseTemp != null) {
                teacherCourseVO.setCourseName(courseTemp.getCourseName());
            }
            return teacherCourseVO;
        }).collect(Collectors.toList());
        page.setRecords(result);
        page.setTotal(teacherCourseVOIPage.getTotal());
        return page;
    }

    @Override
    public TeacherCourseVO addTeacherCourse(AddTeacherCourseDTO addTeacherCourseDTO, HttpServletRequest request) {
        // 非空判断
        if (addTeacherCourseDTO == null ||
                addTeacherCourseDTO.getTeacherId() == null ||
                addTeacherCourseDTO.getCourseId() == null ||
                addTeacherCourseDTO.getClassId() == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR);
        }
        // 提取变量
        Integer classId = addTeacherCourseDTO.getClassId();
        Integer courseId = addTeacherCourseDTO.getCourseId();
        Integer teacherId = addTeacherCourseDTO.getTeacherId();

        // 获取参数 查看是否存在
        web.stu.model.entity.Class aClass = classService.getById(classId);
        Course course = courseService.getById(courseId);
        User teacher = userService.getById(teacherId);
        if (aClass == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标班级不存在");
        }
        if (course == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标课程不存在");
        }
        if (teacher == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标教师不存在");
        }

        // 判断是否存在相同的记录
        Integer recordCount = teacherCourseMapper.countTeacherCourses(classId, courseId, teacherId);
        if (recordCount > 0) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "该记录已存在");
        }

        // 添加授课教师
        Integer insertRes = teacherCourseMapper.insertTeacherCourse(classId, courseId, teacherId);
        if (insertRes <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加失败");
        }

        // 封装数据
        TeacherCourseVO teacherCourseVO = BeanUtil.copyProperties(addTeacherCourseDTO, TeacherCourseVO.class);
        teacherCourseVO.setTeacherName(teacher.getRealName());
        teacherCourseVO.setCourseName(course.getCourseName());
        teacherCourseVO.setClassName(aClass.getClassName());

        return teacherCourseVO;
    }

    @Override
    public TeacherCourseVO updateTeacherCourse(AddTeacherCourseDTO addTeacherCourseDTO, HttpServletRequest request) {
        // 非空判断
        if (addTeacherCourseDTO == null || addTeacherCourseDTO.getCourseId() == null || addTeacherCourseDTO.getClassId() == null || addTeacherCourseDTO.getTeacherId() == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR);
        }
        // 提取变量
        Integer teacherId = addTeacherCourseDTO.getTeacherId();
        Integer classId = addTeacherCourseDTO.getClassId();
        Integer courseId = addTeacherCourseDTO.getCourseId();

        // 获取参数 查看是否存在
        User teacher = userService.getById(teacherId);
        Course course = courseService.getById(courseId);
        Class aClass = classService.getById(classId);
        if (teacher == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标教师不存在");
        }
        if (course == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标课程不存在");
        }
        if (aClass == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "目标班级不存在");
        }

        // 判断是否存在相同的记录
        Integer recordCount = teacherCourseMapper.countTeacherCourses(classId, courseId, teacherId);
        if (recordCount == 0) {
            // 没有记录才添加 授课教师
            Integer insertRes = teacherCourseMapper.updateTeacherCourseByClassIdCourseId(classId, courseId, teacherId);
            if (insertRes <= 0) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改失败");
            }
        }

        // 封装数据
        TeacherCourseVO teacherCourseVO = BeanUtil.copyProperties(addTeacherCourseDTO, TeacherCourseVO.class);
        teacherCourseVO.setTeacherName(teacher.getRealName());
        teacherCourseVO.setCourseName(course.getCourseName());
        teacherCourseVO.setClassName(aClass.getClassName());
        return teacherCourseVO;
    }


    @Override
    public void deleteTeacherCourse(AddTeacherCourseDTO addTeacherCourseDTO, HttpServletRequest request) {
        // 非空判断
        if (addTeacherCourseDTO == null) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR);
        }
        Integer teacherId = addTeacherCourseDTO.getTeacherId();
        Integer classId = addTeacherCourseDTO.getClassId();
        Integer courseId = addTeacherCourseDTO.getCourseId();

        // 判断该记录是否存在
        Integer i = teacherCourseMapper.countTeacherCourses(classId, courseId, teacherId);
        if (i <= 0) {
            throw new BusinessException(ErrorCode.PRIMARY_ERROR, "删除记录不存在，请联系管理员");
        }

        // 直接移除
        Integer res = teacherCourseMapper.deleteTeacherCourse(classId, courseId, teacherId);
        if (res <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除教师授课记录失败");
        }
    }

}
